import os
import Image
from django.template import Library

register = Library()

def resize(file, x, y, sizeName="", ret=""):
    if "" == sizeName:
        sizeName = str(x) + "x" + str(y)
    # defining the filename and the miniature filename
    filehead, filename = os.path.split(file.path)
    basepath, junk = os.path.split(filehead)
    minipath = os.path.join(basepath, sizeName)
    miniature_filename = os.path.join(minipath, filename)
    created = False
    
    if False == os.path.exists(minipath):
        os.makedirs(minipath)
    
    # define mini url
    filehead, filename = os.path.split(file.url)
    baseurl, junk = os.path.split(filehead)
    miniature_url = baseurl + '/' + sizeName + '/' + filename
    
    if os.path.exists(miniature_filename) and os.path.getmtime(file.path)>os.path.getmtime(miniature_filename):
        os.unlink(miniature_filename)
    # if the image wasn't already resized, resize it

    if not os.path.exists(miniature_filename):
        image = Image.open(file.path)
        image.thumbnail([x, y], Image.ANTIALIAS)
        try:
            image.save(miniature_filename, image.format, quality=90, optimize=1)
        except:
            image.save(miniature_filename, image.format, quality=90)
        created = True
    
    if "w" == ret:
        image = Image.open(miniature_filename)
        return image.size[0]
    elif "h" == ret:
        image = Image.open(miniature_filename)
        return image.size[1]
    else:
        return miniature_url

@register.filter(name='thumbnail')
def thumbnail(file, size='48x48'):
    # defining the size
    x, y = [int(x) for x in size.split('x')]
    return resize(file, x, y, "Thumbnail")

@register.filter(name='small')
def small(file):
    return resize(file, 300, 300, "LowRes")

@register.filter(name='medium')
def medium(file):
    return resize(file, 600, 600, "MedRes")

@register.filter(name='750')
def res750(file):
    return resize(file, 750, 750, "750Res")
@register.filter(name='750w')
def res750w(file):
    return resize(file, 750, 750, "750Res", "w")
@register.filter(name='750h')
def res750h(file):
    return resize(file, 750, 750, "750Res", "h")
@register.filter(name='750h20')
def res750h20(file):
    return resize(file, 750, 750, "750Res", "h") + 20
@register.filter(name='750h254')
def res750h254(file):
    return resize(file, 750, 750, "750Res", "h") + 254

@register.filter(name='large')
def large(file):
    return resize(file, 1024, 1024, "HighRes")

